package sort;


/**
 * 冒泡排序
 */
public class BubbleSort {
    public static void main(String[] args) {
        int[] array = {1,2,3,5,7,6,9,8,10};
        bubbleSort(array);
        for (int x: array) {
            System.out.print(x + " ");
        }

    }
    public static void bubbleSort(int[] elem){
        //优化冒泡排序,判断在排序时元素是否已经有序，避免不必要的交换
        int flag = 0;
        for (int i = 0; i < elem.length - 1; i++) {
            //elem.length - i 减少比较趟数，在每次交换，放到后面的元素已经排序好了
            for (int j = 0; j < elem.length- 1 - i; j++) {
                if(elem[j] > elem[j + 1]){
                    swap(elem,j,j + 1);
                    flag = 1;
                }
            }
            if(flag == 0){
                break;
            }
        }
    }
    public static void swap(int[] elem,int start,int end){
        int cur = elem[start];
        elem[start] = elem[end];
        elem[end] = cur;
    }
}
